package fr.tocchisu.grepolis.requests;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import fr.tocchisu.grepolis.model.SendUnit;
import fr.tocchisu.grepolis.model.Town;

public class SupportRequest extends AbstractHTTPRequest {

	private Town town;
	private List<SendUnit> attackUnits;
	private int targetedTown;

	public SupportRequest(Town town, int targetedTown, SendUnit... attackUnits) {
		this.town = town;
		this.attackUnits = Arrays.asList(attackUnits);
		this.targetedTown = targetedTown;
	}

	@Override
	protected String getURL() {
		return "town_info?action=send_units&town_id=" + town.getId() + "&h=" + H;
	}

	@Override
	protected String getPostDatas() {
		StringBuilder result = new StringBuilder("{");
		List<String> attackUnitsParams = new ArrayList<String>(attackUnits.size());
		for (SendUnit attackUnit : attackUnits) {
			String unitName = attackUnit.getUnit().name().toLowerCase();
			String unitNumber = Integer.toString(attackUnit.getNumber());
			if (Integer.parseInt(unitNumber) > 0) {
				attackUnitsParams.add("\"" + unitName + "\":" + unitNumber);
			}

		}
		result.append(StringUtils.join(attackUnitsParams, ","));
		result.append(",\"id\":" + targetedTown);
		result.append(",\"type\":\"support\",\"town_id\":\"" + town.getId() + "\",\"nlreq_id\":22468706");
		result.append("}");
		try {
			return "json=" + URLEncoder.encode(result.toString(), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			System.out.println("Bad encoding");
			System.exit(0);
			return null;
		}
	}
	// Town : matra
	// Target date (dd/MM/yy hh:mm:ss) : 20/03/13 10:55:27
	// Target town id: 32406
}
